package dbserver;

import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;

public class QueueManager implements Observer {
	private LinkedBlockingQueue<Query> queryQueue;
	private Query currentQuery;
	private ArrayList<Listener> listeners;
	
	public QueueManager(LinkedBlockingQueue<Query> queryQueue) {
		this.queryQueue = queryQueue;
		listeners = new ArrayList<Listener>();
	}

	public void putQuery(Query query){
		queryQueue.add(query);
	}
	public Query getQuery(){
		try {
			currentQuery = queryQueue.take();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return currentQuery;
	}
	public void addListener(Listener listener){
		synchronized (listeners){
			listeners.add(listener);
		}
	}
	@Override
	public void update(Model model) {
		synchronized (listeners){
			for(Listener l: listeners){
				l.send("" + model.getCurrentState().getId()
						+ "#" + model.getCurrentState().getTerm()
						+ "#" + model.getCurrentState().getValue(), currentQuery.getClientID());
			}
		}
	}
	
}
